package com.os.crm.controller;

import com.os.crm.pojo.DataTask;
import com.os.crm.pojo.Enterprise;
import com.os.crm.service.DataTaskService;
import com.os.crm.service.POIService;
import com.os.sys.service.bean.UserInfo;
import com.os.util.Tools;
import com.os.util.page.PageRequest;
import com.os.util.page.PageResult;
import entity.Param;
import entity.Result;
import entity.StatusCode;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/dataTask")
@RefreshScope
@Slf4j
public class DataTaskController {
    @Autowired
    private DataTaskService dataTaskService;
    @Autowired
    private POIService poiService;
    
    @ApiOperation(value = "分页查询数据采集任务列表信息" , notes = "分页查询数据采集任务列表信息")
    @RequestMapping(value="/selectByPage", method=RequestMethod.GET)
    public Result selectByPage(@RequestParam(value="page",required = false) Integer page,
                               @RequestParam(value="pageSize",required = false) Integer pageSize
                              ,@RequestParam(value="task_name",required = false) String task_name
                              ,@RequestParam(value="keyword",required = false) String keyword
                              ,@RequestParam(value="business_name",required = false) String business_name
                              ,@RequestParam(value="region_name",required = false) String region_name
                              ,@RequestParam(value="execute_type",required = false) String execute_type
                              ,@RequestParam(value="task_type",required = false) String task_type
                              ,@RequestParam(value="source_type",required = false) String source_type
                              ,@RequestParam(value="create_by",required = false) String create_by
        ){
        Map map = new HashMap();
        List paramList = new ArrayList();
        if(task_name!=null){
            paramList.add(new Param("task_name", task_name + "", "String","like"));
        }
        if(create_by!=null){
            paramList.add(new Param("create_by", create_by + "", "Int","="));
        }
        if(keyword!=null){
            paramList.add(new Param("keyword", keyword + "", "String","like"));
        }
        if(business_name!=null){
            paramList.add(new Param("business_name", business_name + "", "String","like"));
        }
        if(region_name!=null){
            paramList.add(new Param("region_name", region_name + "", "String","like"));
        }
        if(execute_type!=null){
            paramList.add(new Param("execute_type", execute_type + "", "String","like"));
        }
        if(task_type!=null){
            paramList.add(new Param("task_type", task_type + "", "String","like"));
        }
        if(source_type!=null){
            paramList.add(new Param("source_type", source_type + "", "String","like"));
        }
        map.put("condstr", Tools.genCondStr("", paramList));
        PageRequest pageRequest = new PageRequest();
        pageRequest.setPageNum(page);
        pageRequest.setPageSize(pageSize);
        PageResult pageResult = dataTaskService.selectByPage(pageRequest,map);
        Result result = new Result(true, StatusCode.OK,"查询成功",pageResult.getContent());
        result.setTotalCount(pageResult.getTotalSize());
        return result;
    }
    @ApiOperation(value = "按照ID查询数据采集任务信息" , notes = "按照ID查询数据采集任务信息")
    @ApiImplicitParam(name = "task_id",value = "ID",required = true,dataType = "int")
    @RequestMapping(value="/selectById/{task_id}", method=RequestMethod.GET)
    public Result selectById(@PathVariable int task_id){
        return new Result(true, StatusCode.OK,"查询成功", dataTaskService.selectById(task_id));
    }
    @ApiOperation(value = "新增数据采集任务信息" , notes = "新增数据采集任务信息")
    @RequestMapping(value="/add",method = RequestMethod.POST)
    public Result insert(@RequestBody DataTask dataTask){
        dataTaskService.insert(dataTask);
        return new Result(true, StatusCode.OK,"添加成功");
    }
    @ApiOperation(value = "更新数据采集任务信息" , notes = "更新数据采集任务信息")
    @RequestMapping(value="/update",method = RequestMethod.POST)
    public Result update(@RequestBody DataTask dataTask){
        dataTaskService.update(dataTask);
        return new Result(true, StatusCode.OK,"修改成功", dataTask);
    }
    @ApiOperation(value = "删除数据采集任务信息" , notes = "删除数据采集任务信息")
    @RequestMapping(value="/{task_id}",method = RequestMethod.DELETE)
    public Result delete(@PathVariable int task_id){
        dataTaskService.deleteById(task_id);
        return new Result(true, StatusCode.OK,"删除成功");
    }

    @ApiOperation(value = "新增数据采集任务信息" , notes = "新增数据采集任务信息-手机端用")
    @RequestMapping(value="/saveDataTask",method = RequestMethod.POST)
    public Result saveDataTask(@RequestBody DataTask dataTask){
        dataTaskService.saveDataTask(dataTask);
        return new Result(true, StatusCode.OK,"添加成功");
    }
    @ApiOperation(value = "按照ID查询数据采集任务信息" , notes = "按照ID查询数据采集任务信息")
    @ApiImplicitParam(name = "task_id",value = "ID",required = true,dataType = "int")
    @RequestMapping(value="/selectTaskDetail", method=RequestMethod.GET)
    public Result selectTaskDetail(@RequestParam int task_id){
        return new Result(true, StatusCode.OK,"查询成功",
                dataTaskService.selectTaskDetail(task_id).getEnterpriseList());
    }

    /**
     * 导出Excel
     * 模版位置: files\template
     * @param request
     * @param response
     */
    @RequestMapping(value="/doExportExcel", method=RequestMethod.GET)
    public void doExportExcel(HttpServletRequest request, HttpServletResponse response, @RequestParam int task_id)
            throws IOException {
        DataTask dataTask = dataTaskService.selectTaskDetail(task_id);
        List<Enterprise> enterpriseList = dataTask.getEnterpriseList();
        response.setContentType("text/json; charset=UTF-8");
        String base = request.getSession().getServletContext().getRealPath("");
        UserInfo userinfo = (UserInfo)request.getSession().getAttribute("userinfo");
        String sheet_type = "";//lend.getLendtype_key() ;
        String file_path = poiService.genExcel4EnterpriseList(userinfo, base, enterpriseList, new HashMap());
        //String file_name = POIBO.getTemplateNameCn(sheet_type)+Tools.getTimeMillStr()+".xlsx";
        String file_name = dataTask.getTask_name()+".xlsx";
        File file = new File(file_path);
        response.setContentType("application/octet-stream");
        //fileName = new String(fileName.getBytes("gb2312"),"ISO8859_1");
        //如 测试文件.doc
        //file_name = new String(file_name.getBytes("gb2312"),"utf-8");
        file_name = new String(file_name.getBytes("gbk"),"ISO8859_1");
        if(!file_name.equals("") && !file_path.equals("") && file_name.indexOf(".") == -1){
            file_name += file_path.substring(file_path.lastIndexOf("."));
        }
        response.setHeader("Content-Disposition", "attachment;filename=\"" + file_name + "" + "\"");
        int len = (int)file.length();
        byte []buf = new byte[len];
        FileInputStream fis = new FileInputStream(file);
        OutputStream out = response.getOutputStream();
        len = fis.read(buf);
        out.write(buf, 0, len);
        out.flush();
        fis.close();
    }
}